#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2015  Data Enlighten Technology (Beijing) Co.,Ltd

import os
import requests
import requests.cookies
import json
import base64

from mj_parser import common_errors
import Lib.Logger.log4py as logging


class GMWebSource:
    URL = 'https://dpj.saic-gm.com/epcoloe4dealer/rest/vehicles/'
    LOGIN = "http://139.196.81.58:888/login/init/2c2eb642-cbb4-4ec5-8401-f68804d92deb/935ece89864f46f9a6cb73ad9154c0f2"

    def __init__(self, root_path='.'):
        self.logger = logging.get_logger('crawler', 'GMWebSource')
        self.root_path = root_path
        self.conf_path = os.path.join(root_path, 'conf')
        self.session_file = os.path.join(self.conf_path, 'gm_session.txt')
        self.data_path = os.path.join(root_path, "data")
        self.session = None
        self.load_session()

    def get_data(self, str_vin, brand, group):
        response = self.query_vin(str_vin)
        if response is None:
            return common_errors.ERR_TCP_ERROR, None

        vin_file = os.path.join(self.data_path, '{0}.json'.format(str_vin))
        with open(vin_file, 'wb') as fo:
            fo.write(response)

        return common_errors.ERR_SUCCESS, vin_file

    def query_vin(self, str_vin):
        if self.session is None:
            self.login()

        querystring = {"_dc": "1493368323614"}
        headers = {
            'accept': "application/json, text/plain, */*",
            'user-agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
            'accept-encoding': "gzip, deflate, sdch, br",
            'accept-language': "zh-CN,zh;q=0.8,en;q=0.6",
            'cookie': self.session['cookies']
        }

        vin_url = GMWebSource.URL + str_vin
        response = requests.request("GET", vin_url, headers=headers, params=querystring, verify=False)
        if response.status_code == 200 and (response.content.decode('utf-8').find('<title>登入页面</title>') < 0 and response.content.decode('utf-8').find('redirectUrl') < 0):
            return response.content

        self.logger.error('need login again: return %s' % response.status_code)
        member = self.session['member']
        if int(member['loginTime']) >= int(member['limitLoginTime']):
            self.logger.error("Exceeded login limit")
            self.logger.error(response.content)
            return None

        self.login()
        headers = {
            'accept': "application/json, text/plain, */*",
            'user-agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
            'accept-encoding': "gzip, deflate, sdch, br",
            'accept-language': "zh-CN,zh;q=0.8,en;q=0.6",
            'cookie': self.session['cookies']
        }
        response = requests.request("GET", vin_url, headers=headers, params=querystring, verify=False)
        if response.status_code == 200:
            return response.content

        return None


    def login(self):
        response = requests.get(GMWebSource.LOGIN)
        self.session = json.loads(base64.b64decode(response.content.decode('utf-8')).decode('utf-8'))
        self.save_session()

    def save_session(self):
        if not os.path.exists(self.conf_path):
            os.makedirs(self.conf_path)
        with open(self.session_file, 'w') as fo:
            json.dump(self.session, fo)

    def load_session(self):
        self.session = None
        if not os.path.exists(self.session_file):
            return None
        with open(self.session_file, 'r') as fi:
            try:
                self.session = json.load(fi)
            except Exception as e:
                self.logger.error(str(e))

if __name__ == '__main__':
    source = GMWebSource()
    source.get_data('LSGNB83L5HA032814', '', '')
